import { timezoneHandler } from './timezone-handler.js';

/**
 * 直播日程组件
 * 显示直播时间并处理时区转换
 */
export class LiveSchedule {
    constructor(elementId) {
        this.element = document.getElementById(elementId);
        this.currentTimezone = timezoneHandler.getUserTimezone();
        this.liveStartTime = null;
        this.init();
    }

    /**
     * 初始化组件
     */
    init() {
        // 创建时区选择器
        this.createTimezoneSelector();
        
        // 更新时区显示
        this.updateTimezoneDisplay();
        
        // 监听时区变化
        document.getElementById('timezone-selector').addEventListener('change', (e) => {
            this.currentTimezone = e.target.value;
            this.updateTimezoneDisplay();
        });
    }

    /**
     * 设置直播开始时间
     * @param {Date|string} startTime 直播开始时间
     */
    setLiveStartTime(startTime) {
        this.liveStartTime = startTime;
        this.updateTimezoneDisplay();
    }

    /**
     * 创建时区选择器
     */
    createTimezoneSelector() {
        const timezoneSelector = document.createElement('select');
        timezoneSelector.id = 'timezone-selector';
        timezoneSelector.className = 'px-3 py-2 rounded-lg border border-gray-200 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary transition-all';
        
        // 添加时区选项
        timezoneHandler.getSupportedTimezones().forEach(timezone => {
            const option = document.createElement('option');
            option.value = timezone.id;
            option.textContent = `${timezone.name} (GMT${timezone.offset >= 0 ? '+' : ''}${timezone.offset})`;
            if (timezone.id === this.currentTimezone) {
                option.selected = true;
            }
            timezoneSelector.appendChild(option);
        });
        
        // 添加到组件
        const selectorContainer = document.createElement('div');
        selectorContainer.className = 'mb-4';
        selectorContainer.appendChild(timezoneSelector);
        
        this.element.appendChild(selectorContainer);
    }

    /**
     * 更新时区显示
     */
    updateTimezoneDisplay() {
        if (!this.liveStartTime) return;
        
        // 清除现有内容
        const timeElements = this.element.querySelectorAll('.live-time-display');
        timeElements.forEach(el => el.remove());
        
        // 创建时间显示元素
        const timeDisplay = document.createElement('div');
        timeDisplay.className = 'live-time-display p-4 bg-white rounded-lg shadow-sm mb-4';
        
        // 显示当前时区
        const timezoneInfo = timezoneHandler.getSupportedTimezones().find(tz => tz.id === this.currentTimezone);
        const timezoneName = timezoneInfo ? timezoneInfo.name : this.currentTimezone;
        
        // 格式化直播时间
        const formattedTime = timezoneHandler.formatDateTime(
            this.liveStartTime, 
            this.currentTimezone, 
            { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric', hour: '2-digit', minute: '2-digit' }
        );
        
        // 计算与默认时区的时差
        const timeDiff = timezoneHandler.getTimeDifference(
            timezoneHandler.defaultTimezone,
            this.currentTimezone
        );
        
        // 构建内容
        timeDisplay.innerHTML = `
            <div class="font-medium text-gray-700 mb-2">直播时间 (${timezoneName}):</div>
            <div class="text-2xl font-bold text-primary mb-2">${formattedTime}</div>
            <div class="text-sm text-gray-500">
                ${timeDiff !== 0 ? `与北京时间相差 ${timeDiff > 0 ? '+' : ''}${timeDiff} 小时` : '与北京时间相同'}
            </div>
            <div class="mt-3 text-sm">
                ${timezoneHandler.formatLiveStartTime(this.liveStartTime, this.currentTimezone)}
            </div>
        `;
        
        // 添加倒计时
        this.addCountdown(timeDisplay);
        
        // 添加到组件
        this.element.appendChild(timeDisplay);
    }

    /**
     * 添加倒计时
     * @param {HTMLElement} container 容器元素
     */
    addCountdown(container) {
        const countdownElement = document.createElement('div');
        countdownElement.className = 'mt-4 pt-4 border-t border-gray-100';
        
        container.appendChild(countdownElement);
        
        // 更新倒计时
        const updateCountdown = () => {
            if (!this.liveStartTime) return;
            
            const now = new Date();
            const startDate = typeof this.liveStartTime === 'string' ? new Date(this.liveStartTime) : this.liveStartTime;
            
            // 如果提供了时区，先转换为该时区的时间
            if (this.currentTimezone && this.currentTimezone !== timezoneHandler.defaultTimezone) {
                var targetStartDate = timezoneHandler.convertTimezone(
                    startDate, 
                    timezoneHandler.defaultTimezone, 
                    this.currentTimezone
                );
            } else {
                var targetStartDate = new Date(startDate);
            }
            
            // 计算时间差
            const timeDiff = targetStartDate - now;
            
            // 如果直播已开始
            if (timeDiff <= 0) {
                countdownElement.innerHTML = `
                    <div class="flex items-center justify-center">
                        <span class="inline-flex items-center px-3 py-1 rounded-full bg-success/10 text-success text-sm font-medium">
                            <i class="fa fa-circle text-success text-xs mr-1 animate-pulse"></i> 直播进行中
                        </span>
                    </div>
                `;
                return;
            }
            
            // 计算天、时、分、秒
            const days = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
            const hours = Math.floor((timeDiff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
            const minutes = Math.floor((timeDiff % (1000 * 60 * 60)) / (1000 * 60));
            const seconds = Math.floor((timeDiff % (1000 * 60)) / 1000);
            
            // 构建倒计时显示
            let countdownHtml = '<div class="flex items-center justify-center space-x-2">';
            
            if (days > 0) {
                countdownHtml += `
                    <div class="bg-gray-800 text-white px-2 py-1 rounded text-center">
                        <div class="text-lg font-bold">${days}</div>
                        <div class="text-xs">天</div>
                    </div>
                `;
            }
            
            countdownHtml += `
                <div class="bg-gray-800 text-white px-2 py-1 rounded text-center">
                    <div class="text-lg font-bold">${hours.toString().padStart(2, '0')}</div>
                    <div class="text-xs">时</div>
                </div>
                <div class="text-gray-500 text-lg">:</div>
                <div class="bg-gray-800 text-white px-2 py-1 rounded text-center">
                    <div class="text-lg font-bold">${minutes.toString().padStart(2, '0')}</div>
                    <div class="text-xs">分</div>
                </div>
                <div class="text-gray-500 text-lg">:</div>
                <div class="bg-gray-800 text-white px-2 py-1 rounded text-center">
                    <div class="text-lg font-bold">${seconds.toString().padStart(2, '0')}</div>
                    <div class="text-xs">秒</div>
                </div>
            </div>
            <div class="mt-2 text-center text-sm text-gray-500">直播开始倒计时</div>
            `;
            
            countdownElement.innerHTML = countdownHtml;
        };
        
        // 初始更新
        updateCountdown();
        
        // 每秒更新一次
        this.countdownInterval = setInterval(updateCountdown, 1000);
    }

    /**
     * 销毁组件
     */
    destroy() {
        if (this.countdownInterval) {
            clearInterval(this.countdownInterval);
        }
    }
}    